class PurchaseController < ApplicationController
  before_filter :user_authorize, :except =>[:getPurchasesForIndex]
  before_filter :sys_before_log
  before_filter :privilege_filter,:except =>[:newPurchase,:purchaseView,:rejectReason,:purchaseForAuditing,:purchaseListForAuditor]

  def newPurchase
    
  end

  def newPurchaseForProduct
    
  end

  def purchaseForApplicant
    
  end

  def purchaseForAuditing
    
  end

  def purchaseForAuditor
    
  end

  def purchaseForRelease
    
  end

  def purchaseForVendor
    
  end

  def purchaseListForApplicant
    
  end

  def purchaseListForApplicantBySearch
    
  end

  def purchaseListForAuditor
    @role = session[:is_chief].to_i
  end

  def purchaseListForIndex
    
  end

  def purchaseListForVendorBySearch
    
  end

  def purchaseView

  end

  def rejectReason
    
  end

  def rejectReasonView
    
  end

  #主页显示采购列表
  def getPurchasesForIndex
    pageBegin =  params[:start]
    pageEnd =  params[:limit]
    searchType = 'release'
    conditionsStr = ""
    conditionsHash = Hash.new

    if conditionsStr == ""
      conditionsStr = "is_locked <> 1 "
    else
      conditionsStr = conditionsStr + " AND is_locked <> 1"
    end

    conditionsStr = conditionsStr + " AND release_status = :release_status AND end_date >= :end_date AND is_terminated = :is_terminated"
    conditionsHash[:release_status] = '已发布'
    conditionsHash[:end_date] = Time.now.strftime("%Y-%m-%d")
    conditionsHash[:is_terminated] = '否'
    purchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash],:offset=>pageBegin.to_s,:limit =>pageEnd.to_s,:order=>'updated_at DESC')
    allPurchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash])
    jsonstr = "{totalProperty:"+allPurchases.length.to_s+",root:"+purchases.to_json()+"}"
    logger.info jsonstr
    render :text=>jsonstr, :layout=>false
  end
  
  def getPurchasesForApplicant
    pageBegin =  params[:start]
    pageEnd =  params[:limit]
    
    #searchtype为nil说明，用户是从我的采购中进行查询的，否则是从申购单中进行查询的。
    conditionsStr = ""
    conditionsHash = Hash.new

    conditionsHash[:applicant_id] = session[:applicant_id]
    #申购单从新编写，如果不是部门管理员，就只显示自己的，如果是管理员就显示所有符合条件的
    if session[:is_dept_manager] == "no"
      #非部门管理员，只显示自己相关的。
      conditionsStr = 'applicant_id = :applicant_id'
      conditionsHash[:applicant_id] = session[:applicant_id]
    else
      #非管理员，只显示自己相关的。
      conditionsStr = 'department_id = :department_id'
      conditionsHash[:department_id] = session[:department_id]

      #如果指定了申购人，则添加申购人条件
      if params[:applicant_id] != nil && params[:applicant_id] != ""
        if conditionsStr == ""
          conditionsStr = "applicant_id = :applicant_id"
        else
          conditionsStr = conditionsStr + " AND applicant_id = :applicant_id"
        end
        conditionsHash[:applicant_id] = params[:applicant_id]
      end
    end

    #以下为公共条件
    #按产品名称查询
    if params[:product_name] != nil && params[:product_name] != ""
      if conditionsStr == ""
        conditionsStr = "product_name = :product_name"
      else
        conditionsStr = conditionsStr + " AND product_name like :product_name"
      end
      conditionsHash[:product_name] = '%' + params[:product_name] + '%'
    end
    
    #按申购序号
    if params[:order_number] != nil && params[:order_number] != ""
      if conditionsStr == ""
        conditionsStr = "seq_number = :seq_number"
      else
        conditionsStr = conditionsStr + " AND seq_number = :seq_number"
      end
      conditionsHash[:seq_number] = params[:order_number]
    end

    if params[:unit_price_from] != nil && params[:unit_price_from] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_price >= :unit_price_from"
      else
        conditionsStr = conditionsStr + " AND estimated_price >= :unit_price_from"
      end
      conditionsHash[:unit_price_from] = params[:unit_price_from]
    end

    if params[:unit_price_to] != nil && params[:unit_price_to] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_price <= :unit_price_to"
      else
        conditionsStr = conditionsStr + " AND estimated_price <= :unit_price_to"
      end
      conditionsHash[:unit_price_to] = params[:unit_price_to]
    end

    if params[:amount_from] != nil && params[:amount_from] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_amount >= :amount_from"
      else
        conditionsStr = conditionsStr + " AND estimated_amount >= :amount_from"
      end
      conditionsHash[:amount_from] = params[:amount_from]
    end

    if params[:amount_to] != nil && params[:amount_to] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_amount <= :amount_to"
      else
        conditionsStr = conditionsStr + " AND estimated_amount <= :amount_to"
      end
      conditionsHash[:amount_to] = params[:amount_to]
    end
      
    allPurchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash])
    purchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash],:limit =>pageBegin.to_s+","+pageEnd.to_s,:order=>'updated_at DESC')
    jsonstr = "{totalProperty:"+allPurchases.length.to_s+",root:"+purchases.to_json(:include => {:applicant => {:only => :name}})+"}"
    logger.info jsonstr
    render :text=>jsonstr, :layout=>false
  end

  #审批人用
  def getPurchasesForAuditor
    pageBegin =  params[:start]
    pageEnd =  params[:limit]
    auditor = Auditor.find(session[:auditor_id])
    #2011-08-16，改为搜索出所有的申购订单
    conditionsStr = ""
    conditionsHash = Hash.new
    conditionsStr = "purchase_type = :purchase_type"
    if session[:auditor_type] == 0
      conditionsHash[:purchase_type] = 0
    elsif session[:auditor_type] == 1
      conditionsHash[:purchase_type] = 1
    end

    #以下为公共条件
    #
    #如果指定了申购人，则添加申购人条件
    if params[:applicant_id] != nil && params[:applicant_id] != ""
      if conditionsStr == ""
        conditionsStr = "applicant_id = :applicant_id"
      else
        conditionsStr = conditionsStr + " AND applicant_id = :applicant_id"
      end
      conditionsHash[:applicant_id] = params[:applicant_id]
    end
    
    #按产品名称查询
    if params[:product_name] != nil && params[:product_name] != ""
      if conditionsStr == ""
        conditionsStr = "product_name = :product_name"
      else
        conditionsStr = conditionsStr + " AND product_name like :product_name"
      end
      conditionsHash[:product_name] = '%' + params[:product_name] + '%'
    end

    #按申购序号
    if params[:order_number] != nil && params[:order_number] != ""
      if conditionsStr == ""
        conditionsStr = "seq_number = :seq_number"
      else
        conditionsStr = conditionsStr + " AND seq_number = :seq_number"
      end
      conditionsHash[:seq_number] = params[:order_number]
    end

    if params[:unit_price_from] != nil && params[:unit_price_from] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_price >= :unit_price_from"
      else
        conditionsStr = conditionsStr + " AND estimated_price >= :unit_price_from"
      end
      conditionsHash[:unit_price_from] = params[:unit_price_from]
    end

    if params[:unit_price_to] != nil && params[:unit_price_to] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_price <= :unit_price_to"
      else
        conditionsStr = conditionsStr + " AND estimated_price <= :unit_price_to"
      end
      conditionsHash[:unit_price_to] = params[:unit_price_to]
    end

    if params[:amount_from] != nil && params[:amount_from] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_amount >= :amount_from"
      else
        conditionsStr = conditionsStr + " AND estimated_amount >= :amount_from"
      end
      conditionsHash[:amount_from] = params[:amount_from]
    end

    if params[:amount_to] != nil && params[:amount_to] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_amount <= :amount_to"
      else
        conditionsStr = conditionsStr + " AND estimated_amount <= :amount_to"
      end
      conditionsHash[:amount_to] = params[:amount_to]
    end
    
    allPurchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash])
    purchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash],:limit =>pageBegin+","+pageEnd,:include=>[:auditor,:dept_leader,:leader],:order=>'updated_at DESC')
    jsonstr = "{totalProperty:"+allPurchases.length.to_s+",root:"+purchases.to_json(:include=>[:auditor,:dept_leader,:leader])+"}"
    logger.info jsonstr
    render :text=>jsonstr, :layout=>false
  end

  #供应商专用
  def getPurchasesForVendor
    pageBegin =  params[:start]
    pageEnd =  params[:limit]
    #searchtype为nil说明，用户是从我的采购中进行查询的，否则是从申购单中进行查询的。
    conditionsStr = ""
    conditionsHash = Hash.new
    if params[:product_name] != nil && params[:product_name] != ""
      conditionsStr = "product_name like :product_name"
      conditionsHash[:product_name] = "%"+params[:product_name]+"%"
    end
    
    if params[:unit_price_from] != nil && params[:unit_price_from] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_price >= :unit_price_from"
      else
        conditionsStr = conditionsStr + " AND estimated_price >= :unit_price_from"
      end
      conditionsHash[:unit_price_from] = params[:unit_price_from]
    end

    if params[:unit_price_to] != nil && params[:unit_price_to] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_price <= :unit_price_to"
      else
        conditionsStr = conditionsStr + " AND estimated_price <= :unit_price_to"
      end
      conditionsHash[:unit_price_to] = params[:unit_price_to]
    end

    if params[:amount_from] != nil && params[:amount_from] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_amount >= :amount_from"
      else
        conditionsStr = conditionsStr + " AND estimated_amount >= :amount_from"
      end
      conditionsHash[:amount_from] = params[:amount_from]
    end

    if params[:amount_to] != nil && params[:amount_to] != ""
      if conditionsStr == ""
        conditionsStr = "estimated_amount <= :amount_to"
      else
        conditionsStr = conditionsStr + " AND estimated_amount <= :amount_to"
      end
      conditionsHash[:amount_to] = params[:amount_to]
    end

    if conditionsStr == ""
      conditionsStr = "is_locked <> 1 "
    else
      conditionsStr = conditionsStr + " AND is_locked <> 1"
    end

    conditionsStr = conditionsStr + " AND release_status = :release_status"
    conditionsHash[:release_status] = '已发布'
      
    searchType = params[:search_type]
    #竞价信息
    if searchType == "bidding"
      conditionsStr = conditionsStr + " AND end_date >= :end_date AND is_terminated='否' AND id not in (select purchase_id from offers where vendor_id = :vendor_id)"
      conditionsHash[:end_date] = Time.now.strftime("%Y-%m-%d")
      conditionsHash[:vendor_id] = session[:vendor_id]
      #purchases = Purchase.find(:all,:conditions=>["is_locked <> 1 AND auditing_status = ? AND release_status = ? AND end_date >= ?",'通过',"已发布",Time.now.strftime("%Y-%m-%d")])
      
      #已参与竞价信息。
    elsif searchType == "participation"
      conditionsStr = conditionsStr + " AND primary_status = '否' AND is_terminated = '否' AND id in (select purchase_id from offers where vendor_id = :vendor_id)"
      conditionsHash[:vendor_id] = session[:vendor_id]
      
      #purchases =  Purchase.find(:all, :conditions => ["is_locked <> 1 AND id in (select purchase_id from offers where vendor_id = 1)"])
      #竞价成功信息
    elsif searchType == "win"
      conditionsStr = conditionsStr + " AND vendor_id = :vendor_id AND primary_status = '通过'"
      conditionsHash[:vendor_id] = session[:vendor_id]
      
      #purchases = Purchase.find(:all,:conditions=>["is_locked <> 1 AND auditing_status = ? AND release_status = ? AND vendor_id = ?",'通过',"已发布",session[:vendor_id]])
      #竞价未成功信息
    elsif searchType == "failure"
      conditionsStr = conditionsStr + " AND ((vendor_id is not null AND vendor_id <> :vendor_id) OR (is_terminated = '是')) AND id in (select purchase_id from offers where vendor_id = :vendor_id)"
      conditionsHash[:vendor_id] = session[:vendor_id]
      #purchases = Purchase.find(:all,:conditions=>["is_locked <> 1 AND auditing_status = ? AND release_status = ? AND vendor_id <> ? AND vendor_id is not null",'通过',"已发布",session[:vendor_id]])
    end
    allPurchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash])
    purchases = Purchase.find(:all,:conditions=>[conditionsStr,conditionsHash],:limit =>pageBegin.to_s+","+pageEnd.to_s,:order=>'updated_at DESC')
    jsonstr = "{totalProperty:"+allPurchases.length.to_s+",root:"+purchases.to_json()+"}"
    logger.info "searchType"
    logger.info searchType
    logger.info jsonstr
    render :text=>jsonstr, :layout=>false
  end
  
  def create
    purchase = Purchase.new
    purchase.applicant_id = session[:applicant_id]
    purchase.department_id = session[:department_id]
    purchase.manager = session[:applicant_name]
    purchase.purchase_unit = session[:department_name]
    purchase.action_date = Time.now
    purchase.sub_dept = params[:sub_dept]
    #purchase.category_id = params[:category_id]
    purchase.funding_source = params[:funding_source]
    purchase.funding_account = params[:funding_account]
    purchase.funding_nature = params[:funding_nature]
    purchase.product_name = params[:product_name]
    purchase.service_lift = params[:service_lift]
    purchase.quantity = params[:quantity]
    purchase.brand = params[:brand]
    purchase.model = params[:model]
    purchase.specification = params[:specification]
    purchase.manufacturer = params[:manufacturer]
    purchase.estimated_price = params[:estimated_price]
    purchase.estimated_amount = purchase.estimated_price * purchase.quantity
    purchase.qualification = params[:qualification]

    purchase.purchase_type = params[:purchase_type]

    logger.info params[:purchase_type].to_s+'======================================='
    #purchase.service_request = params[:service_request]
    #purchase.supply_date = params[:supply_date]
    #purchase.supply_address = params[:supply_address]

    purchase.reason = params[:reason]
    purchase.vendor_name = params[:vendor_name]
    purchase.phone = params[:phone]
    purchase.mobile = params[:mobile]

    #开始事务，确保在流水号正常的情况下，一但出现问题，则循环执行
    begin
      Sequence.transaction do
        sequence = Sequence.find(:first,:conditions=>["sub_type = ?",Purchase.name])
        sequence.seq_no = sequence.seq_no + 1
        purchase.seq_number = sequence.seq_no
        purchase.order_number = "SG-" + sequence.seq_no.to_s + "-" + Time.now.strftime("%Y-%m-%d")
        #purchase.order_number = "SG" + Time.now.strftime("%Y%m%d") + sequence.seq_no.to_s
        sequence.save!
        purchase.save!
      end
    rescue ActiveRecord::StaleObjectError
      logger.info "somebody useing sn before yours.............................................................."
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
    rescue Exception => e
      logger.info "logging......................................................................................."
      logger.info e
    end
    info="success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #通过竞价
  def releasePurchase
    purchase = Purchase.find(params[:id])
    purchase.begin_date = params[:begin_date]
    purchase.end_date = params[:end_date]
    purchase.release_status = "已发布"
    purchase.save
    info="success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #供应商竞价。
  def offerForPurchase
    purchase = Purchase.find(params[:id])
    offer = Offer.new
    offer.vendor_id = session[:vendor_id]
    offer.qualification = params[:vendor_qualification]
    offer.service_promise = params[:service_promise]
    offer.product_name = params[:product_name]
    offer.brand = params[:vendor_brand]
    offer.model = params[:vendor_model]
    offer.specification = params[:vendor_specification]
    offer.manufacturer = params[:vendor_manufacturer]
    offer.unit_price = params[:vendor_unit_price]
    offer.amount = params[:vendor_amount]


    purchase.offers << offer
    
    #如果有报价低于，等于预估价，则设置标志位。
    purchase.reload()
    if offer.unit_price < purchase.estimated_price || offer.unit_price == purchase.estimated_price
      purchase.low_price = 1
    end
    
    purchase.save

    info="success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def edit
    purchase = Purchase.find(params[:id])    
    if purchase.offer_id == nil
      rootStr = purchase.to_json(:include=>[:category]);
      #供应商查看已经参与的竞价信息
      if session[:vendor_id] != nil
        offer = Offer.find(:first,:conditions => ['vendor_id = ? AND purchase_id = ?',session[:vendor_id],params[:id]])
        if offer != nil
          rootStr = offer.to_json(:include=>[:purchase]);
        end
      end
    else
      rootStr = purchase.to_json(:include=>[:true_offer,:category]);
      if purchase.primary_status == '否'
        if session[:vendor_id] != nil
          offer = Offer.find(:first,:conditions => ['vendor_id = ? AND purchase_id = ?',session[:vendor_id],params[:id]])
          if offer != nil
            rootStr = offer.to_json(:include=>[:purchase]);
          end
        end
      else
        if session[:vendor_id]!=purchase.vendor_id
          offer = Offer.find(:first,:conditions => ['vendor_id = ? AND purchase_id = ?',session[:vendor_id],params[:id]])
          if offer != nil
            rootStr = offer.to_json(:include=>[:purchase]);
          end
        end
      end
      
    end

    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #部门主管审批通过申购单
  def deptPassPurchase
    begin
      purchase = Purchase.find(params[:purchase_id])
      if purchase
        purchase.dept_auditing = '通过'
        purchase.dept_leader_id = session[:applicant_id]
        purchase.save!
        info = 'success'
      else
        info = '没有该申购单，不能审批通过'
      end
    rescue Exception => e
      info = '审批通过时出错，请重新操作。'
    end
    result = "{success:true,info:'#{info}'}"
    render :text => result,:layout => false
  end

  #部门主管驳回申购单
  def deptRejectPurchase
    begin
      purchase = Purchase.find(params[:id])
      if purchase
        purchase.dept_auditing = '驳回'
        purchase.dept_reject = params[:reson]
        purchase.save!
        info = 'success'
      else
        info = '没有该申购单，请重新操作。'
      end
    rescue Exception => e
      logger.info e.to_s
      info = '驳回申购单时出错，请重新操作。'
    end
    result = "{success:true,info:'#{info}'}"
    render :text => result,:layout => false
  end

  #审批申购单,这里要判断一下，是不是大额的，如果是大额的就在领导部分确认审批，如果是普通的就在auditing_status中审批。
  #也就是说，这个方法是普通管理员，与最高负责人共用的一人提交方法，所以要判断一下用户的角色。
  #如果领导审批则是“提交招标”
  def auditPurchase
    begin
      purchase = Purchase.find(params[:id])
      #判断是否为最高负责人
      if session[:is_chief] == 1
        auditor = Auditor.find(session[:auditor_id])
        #如果超出审批范围则提交招标
        if auditor.unit_price_ceiling <= purchase.estimated_price || auditor.amount_ceiling <= purchase.estimated_amount
          purchase.last_auditing_status = '提交招标'
        else
          purchase.last_auditing_status = '通过'
        end        
        purchase.leader_id = session[:auditor_id]
      else
        purchase.auditing_status = '通过'
        purchase.auditor_id = session[:auditor_id]
      end
      #判断是否超过的最高设定的审批值。
      
      purchase.save!
      info = 'success'
    rescue Exception => e
      info = e.to_s
      logger.info info
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #审批人审查大额申购单
  def checkPurchase
    #这里要判断一下如果是大额的，要补充上处长的审批ID和提交招标状态。
    begin
      purchase = Purchase.find(params[:id])
      purchase.auditing_status = '通过'
      purchase.check_status = '通过'
      purchase.auditor_id = session[:auditor_id]
      purchase.save!
      info = 'success'
    rescue Exception => e
      info = e.to_s
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result,:layout=>false
  end

  #审批人驳回
  def rejectPurchase
    begin
      purchase = Purchase.find(params[:id])
      purchase.reject_reason = params[:reson]
      purchase.auditor_id = session[:auditor_id]
      purchase.auditing_status = '驳回'
      purchase.save!
      info = 'success'
    rescue Exception => e
      info = e.to_s
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #用来检测某供应商是否已经对某申购进行过竞价了。
  def isBid
    purchaseId = params[:id]
    offers = Offer.find(:all,:conditions=>["purchase_id = ? AND vendor_id = ? AND is_locked <> 1",purchaseId,session[:vendor_id]])
    #如果为零，说明没有参与过。
    if offers.length == 0
      info = 'success'
    else
      info = 'failure'
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end


  #得到申购单的驳回原因
  def getRejectReasonOfPurchase
    purchase = Purchase.find(params[:id])
    render :text=>purchase.to_json(:only => [:id,:reject_reason]),:layout=>false
  end

  #终止申购
  def terminatePurchase
    purchase = Purchase.find(params[:id])
    purchase.is_terminated = '是'
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #审批人修改竞价结束时间
  def changeDate
    purchase = Purchase.find(params[:id])
    purchase.end_date = params[:endDate]
    purchase.save
    info = 'success'
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请人，初选
  def primarySelectPurchase
    purchase = Purchase.find(params[:purchase_id])
    purchase.is_primary = '是'
    offer = Offer.find(params[:offer_id])
    offer.bid_status = '初选'
    offer.save
    purchase.vendor_id = offer.vendor_id
    purchase.offer_id = offer.id
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #审批人，允许通过初选
  def passPrimary
    purchase = Purchase.find(params[:id]);
    purchase.primary_status = '通过'
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #审批人，审批时驳回初选
  def rejectPrimary
    purchase = Purchase.find(params[:id]);
    purchase.primary_status = '驳回'
    purchase.primary_audit_opinion = params[:reson]
    logger.info params[:reson]
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请人，通过验收
  def passAcceptance
    purchase = Purchase.find(params[:id]);
    purchase.is_acceptance = '是'
    purchase.acceptance_status = '通过'
    purchase.service_rating = params[:service_rating]
    purchase.quality_rating = params[:quality_rating]
    purchase.acceptance_opinion = params[:acceptance_opinion]
    
    vendor = purchase.vendor
    logger.info vendor
    logger.info vendor.service_rating
    logger.info vendor.supply_count
    #logger.info ((vendor.service_rating * vendor.supply_count + purchase.service_rating)/(vendor.supply_count + 1)).round
    vendor.service_rating = ((vendor.service_rating * vendor.supply_count + purchase.service_rating)/(vendor.supply_count + 1)).round
    vendor.quality_rating = ((vendor.quality_rating * vendor.supply_count + purchase.quality_rating)/(vendor.supply_count + 1)).round
    vendor.supply_count+=1
    vendor.save
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请人，驳回验收
  def rejectAcceptance
    purchase = Purchase.find(params[:id])
    purchase.acceptance_status = '驳回'
    purchase.acceptance_opinion = params[:acceptance_opinion]
    logger.info params[:acceptance_opinion]
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请人，入库
  def entryPurchase
    purchase = Purchase.find(params[:id]);
    logger.info params
    purchase.entry_date = params[:entry_date]
    purchase.entry_order_number = params[:entry_order_number]
    purchase.invoice_number = params[:invoice_number]
    purchase.is_import = params[:is_import]
    purchase.produce_date = params[:produce_date]
    purchase.purchase_date = params[:purchase_date]
    purchase.product_sn = params[:product_sn]
    purchase.item_no = params[:item_no]
    purchase.assignment_unit = params[:assignment_unit]
    purchase.instruction = params[:instruction]
    purchase.remark = params[:remark]
    purchase.is_entry = '是'
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #申请人,报账
  def accountPurchase
    purchase = Purchase.find(params[:id]);
    purchase.is_account = '是'
    purchase.for_account_info = params[:for_account_info]
    purchase.save
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #强制进入初选，对于条件不符合，但管理员强制进入初选的.
  def forPrimary
    purchase = Purchase.find(params[:id]);
    if purchase.offers_count>0
      if purchase.low_price==1
        purchase.force_primary = '是'
        purchase.save
        info = "success"
      else
        info = "供应商的竞价都高于预估价格，不能进入初选"
      end
    else
      info = "没有供应商竞价，不能进入初选"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result,:layout=>false
  end


  #用户查看竞价供应商的报价
  def viewOffer
    offer = Offer.find(params[:id])
    if offer != nil
      rootStr  = offer.to_json()
    end
    jsonStr = "{root:["+rootStr+"]}"
    render :text=>jsonStr,:layout=>false
  end

  #打印申购单
  require "spreadsheet"
  def printPurchase
    Spreadsheet.client_encoding = "UTF-8"
    bookString = StringIO.new
    book = Spreadsheet.open "#{RAILS_ROOT}/public/report_template/template_1.xls"
    #上期未结案件数
    purchase = Purchase.find(params[:id])
    if purchase != nil
      applicant = purchase.applicant
    end
    sheet1 = book.worksheet 0

    sheet1[1,1] = purchase.order_number
    sheet1[1,4] = purchase.action_date.year.to_s+'年'+purchase.action_date.month.to_s+'月'+purchase.action_date.day.to_s+'日'
    sheet1[2,1] = applicant.department.name
    sheet1[2,3] = purchase.sub_dept
    sheet1[2,5] = purchase.manager
    sheet1[3,1] = applicant.login_id
    sheet1[3,3] = applicant.phone
    sheet1[3,5] = applicant.mobile
    sheet1[4,1] = purchase.funding_source
    sheet1[4,3] = purchase.funding_account
    sheet1[4,5] = purchase.funding_nature
    sheet1[5,1] = purchase.product_name
    sheet1[5,3] = purchase.service_lift
    sheet1[5,5] = purchase.quantity
    sheet1[7,0] = purchase.model
    sheet1[7,1] = purchase.manufacturer
    #        if purchase.vendor_id
    #          sheet1[7,2] = purchase.vendor.company_name
    #          sheet1[7,3] = purchase.true_offer.unit_price
    #          sheet1[7,4] = purchase.true_offer.amount
    #        end
    sheet1[7,2] = purchase.vendor_name
    sheet1[7,4] = purchase.estimated_price
    sheet1[7,5] = purchase.estimated_amount
    sheet1[8,1] = purchase.qualification
    sheet1[9,1] = purchase.service_request
        
    time = Time.now

    if purchase.auditor.nil?
      auditorName = ""
    else
      auditorName = purchase.auditor.name
    end

    if purchase.dept_leader.nil?
      deptLeaderName = ""
    else
      deptLeaderName = purchase.dept_leader.name
    end
    
    sheet1[11,1] = time.year.to_s + '年' + time.month.to_s + '月' + time.day.to_s + '日   审批通过   部门主管：' + deptLeaderName
    sheet1[13,1] = time.year.to_s + '年' + time.month.to_s + '月' + time.day.to_s + '日   审批通过   审批人：' + auditorName
    sheet1.each do |row|
      logger.error row[1].to_s
    end
    book.write bookString
    send_data bookString.string,:filename => 'purchase.xls'
  end

  #打印入库单
  require "spreadsheet"
  def printEntry
    Spreadsheet.client_encoding = "UTF-8"
    bookString = StringIO.new
    applicant = Applicant.find(session[:applicant_id])
    book = Spreadsheet.open "#{RAILS_ROOT}/public/report_template/template_2.xls"
    #上期未结案件数
    purchase = Purchase.find(params[:id])
    sheet1 = book.worksheet 0

    sheet1[0,8] = purchase.category.asset_number
    sheet1[1,1] = session[:department_name]
    sheet1[1,3] = purchase.order_number
    sheet1[1,6] = purchase.entry_date.year.to_s+'年'+purchase.entry_date.month.to_s+'月'+purchase.entry_date.day.to_s+'日   第'+purchase.entry_order_number+'号'
    sheet1[3,0] = purchase.product_name
    sheet1[3,1] = purchase.model
    sheet1[3,3] = purchase.quantity
    sheet1[3,4] = purchase.true_offer.unit_price
    sheet1[3,5] = '元'
    sheet1[3,6] = purchase.true_offer.amount
    sheet1[3,7] = '元'
    sheet1[3,8] = purchase.instruction
    sheet1[4,1] = purchase.funding_source
    if purchase.vendor_id
      sheet1[4,3] = purchase.vendor.company_name
    end
    if purchase.offer_id
      sheet1[4,5] = purchase.true_offer.manufacturer
    end
    sheet1[4,7] = purchase.invoice_number
    sheet1[5,7] = purchase.is_entry
    sheet1[6,1] = purchase.produce_date
    sheet1[6,5] = purchase.purchase_date
    sheet1[7,1] = purchase.product_sn
    sheet1[7,5] = purchase.item_no
    sheet1[8,1] = session[:department_name]
    sheet1[8,5] = session[:applicant_name]
    sheet1[10,0] = purchase.remark
        
    sheet1.each do |row|
      logger.error row[1].to_s
    end
    book.write bookString
    send_data bookString.string,:filename => 'entry.xls'
  end

end
